package com.dg11185.nearshop.view;

import java.util.ArrayList;

import com.android.nearshop.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ToggleButton;

/**
 * 
 * @author wanliang527
 * @date 2014-4-23
 */
public class ExpandTabView extends LinearLayout implements OnDismissListener {

    private ToggleButton selectedButton; // 当前被选中的筛选类型按钮
    private ArrayList<View> popupViews = new ArrayList<View>();// 下拉窗口View列表
    private ArrayList<ToggleButton> tabButtons = new ArrayList<ToggleButton>();// Tab按钮列表
    private ArrayList<Integer> icons; // Tab按钮图标列表
    private Context mContext;
    private int displayWidth;
    private int displayHeight;
    private PopupWindow popupWindow;// 下拉窗口
    private int selectedPosition;// 当前被选中的Tab位置
    private OnClickListener popupViewListener;

    private int divider = -1;// 各个Tab之间的分隔线
    private int customButton = -1;// 自定义的Tab样式

    public ExpandTabView(Context context) {
        super(context);
        init(context);
    }

    public ExpandTabView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        mContext = context;
        displayWidth = ((Activity) mContext).getWindowManager()
                .getDefaultDisplay().getWidth();
        displayHeight = ((Activity) mContext).getWindowManager()
                .getDefaultDisplay().getHeight();
        this.setOrientation(LinearLayout.HORIZONTAL);
        // 默认的背景色是白色
        // this.setBackgroundColor(getResources().getColor(android.R.color.white));
    }

    /**
     * 初始化整个View
     * 
     * @param viewArray
     *            popupViews
     * @param icons
     *            图标
     */
    public void initView(ArrayList<View> viewArray, ArrayList<Integer> icons) {
        this.icons = icons;
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        // 设置下拉窗口的大小
        LinearLayout.LayoutParams popupViewLayoutParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, (int) (displayHeight * 0.5));
        // 根据下拉窗口数量设置相应的tab按钮数量
        for (int i = 0; i < viewArray.size(); i++) {
            ToggleButton button = null;
            // 如果没有自定义Tab按钮样式，就使用默认的样式
            if (customButton == -1) {
                button = (ToggleButton) inflater.inflate(
                        R.layout.view_expand_tab_title, null);

            } else {
                button = (ToggleButton) inflater.inflate(customButton, null);
            }

            // 如果指定了Tab按钮图标
            if (icons != null && i < icons.size()) {
                Drawable drawable = mContext.getResources().getDrawable(
                        icons.get(i));
                drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                        drawable.getMinimumHeight());
                button.setCompoundDrawables(drawable, null, null, null);
                // button.setPadding(30, 0, 30, 0);
            }

            button.setTag(i);
            tabButtons.add(button);
            this.addView(button, new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.MATCH_PARENT));
            ((LinearLayout.LayoutParams) button.getLayoutParams()).weight = 1;
            // 添加中间的分割线
            if (i < viewArray.size() - 1) {
                if (divider != -1) {
                    inflater.inflate(divider, this);
                    // this.addView(dividerView);
                }
            }

            // 对popupView进行初始化和一些设置
            LinearLayout popupView = new LinearLayout(mContext);
            // View vv = viewArray.get(i);
            // if (vv.getParent() != null) {
            // ((ViewGroup) vv.getParent()).removeAllViewsInLayout();
            // }
            popupView.addView(viewArray.get(i), popupViewLayoutParams);

            // 设置监听器，使得点击popupwindow以外的区域后，popupwindow可以缩回去
            popupView.setOnClickListener(getPopupViewListener());
            popupViews.add(popupView);

            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToggleButton tButton = (ToggleButton) view;
                    if (selectedButton != null && selectedButton != tButton) {
                        selectedButton.setChecked(false);
                    }
                    selectedButton = tButton;
                    selectedPosition = (Integer) selectedButton.getTag();
                    // 开始下拉窗口的操作
                    startAnimation();
                }
            });
        }
    }

    public void setTabBackground(int resId) {
        if (tabButtons != null) {
            for (int i = 0; i < tabButtons.size(); i++) {
                tabButtons.get(i).setBackgroundResource(resId);
            }
        }
    }

    /**
     * 设置Tab标题
     * 
     * @param valueText
     *            标题名
     * @param position
     *            位置
     */
    public void setTitle(String valueText, int position) {
        if (position < tabButtons.size()) {
            tabButtons.get(position).setText(valueText);
        }
    }

    /**
     * 获取Tab标题
     * 
     * @param position
     *            位置
     * @return 标题名
     */
    public String getTitle(int position) {
        if (position < tabButtons.size()
                && tabButtons.get(position).getText() != null) {
            return tabButtons.get(position).getText().toString();
        }
        return "";
    }

    /**
     * 设置图标
     * 
     * @param position
     *            位置
     * @param iconId
     *            图标ID
     */
    public void setIcon(int position, int iconId) {
        if (icons != null && position < icons.size()) {
            Drawable drawable = mContext.getResources().getDrawable(iconId);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                    drawable.getMinimumHeight());
            tabButtons.get(position).setCompoundDrawables(drawable, null, null,
                    null);
        }
    }

    /**
     * 设置各个Tab栏之间的分割线。需在setValue前调用。
     * 
     * @param divider
     *            分割线
     */
    public void setDivider(int divider) {
        this.divider = divider;
    }

    /**
     * 设置Tab按钮的样式。需在setValue前调用。
     * 
     * @param button
     */
    public void setTabStyle(int res) {
        this.customButton = res;
    }

    public void initView(ArrayList<View> viewArray, String[] tabNames) {
        initView(viewArray, null, tabNames);
    }

    public void initView(ArrayList<View> viewArray, ArrayList<Integer> icons,
            String[] tabNames) {
        initView(viewArray, icons);
        for (int i = 0; i < viewArray.size(); i++) {
            if (i < tabNames.length) {
                setTitle(tabNames[i], i);
            }
        }
    }

    private OnClickListener getPopupViewListener() {
        if (popupViewListener == null) {
            popupViewListener = new OnClickListener() {
                @Override
                public void onClick(View v) {
                    onPressBack();
                }
            };
        }
        return popupViewListener;
    }

    private void startAnimation() {

        if (popupWindow == null) {
            popupWindow = new PopupWindow(popupViews.get(selectedPosition),
                    displayWidth, displayHeight);
            popupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
            // popupWindow.setFocusable(false);
            // popupWindow.setOutsideTouchable(false);
        }

        if (selectedButton.isChecked()) {
            if (!popupWindow.isShowing()) {
                showPopup(selectedPosition);
            } else {
                popupWindow.setOnDismissListener(this);
                popupWindow.dismiss();
                // hideView();
            }
        } else {
            if (popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
        }
    }

    private void showPopup(int position) {
        if (popupWindow.getContentView() != popupViews.get(position)) {
            popupWindow.setContentView(popupViews.get(position));
        }
        popupWindow.showAsDropDown(this, 0, 8);
    }

    /**
     * 如果菜单成展开状态，则让菜单收回去
     */
    public boolean onPressBack() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            if (selectedButton != null) {
                selectedButton.setChecked(false);
            }
            return true;
        } else {
            return false;
        }

    }

    @Override
    public void onDismiss() {
        showPopup(selectedPosition);
        popupWindow.setOnDismissListener(null);
    }

}
